package jp.co.sharp.android.parents.kidsguard.activity.bluetooth;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.app.NotificationCompat;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.android.bluetooth.parentble.ParentBleTransfer;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.bluetooth.adapter.BluetoothItemKnowAdapter;
import jp.co.sharp.android.parents.kidsguard.activity.bluetooth.adapter.BluetoothItemUnknowAdapter;
import jp.co.sharp.android.parents.kidsguard.activity.common.MimamoriContactAddActivity;
import jp.co.sharp.android.parents.kidsguard.activity.home.HomeActivity;
import jp.co.sharp.android.parents.kidsguard.common.DealWithWaitingDlg;
import jp.co.sharp.android.parents.kidsguard.common.DelDeviceConfirmDlg;
import jp.co.sharp.android.parents.kidsguard.common.MimamoriConfirmDlg;
import jp.co.sharp.android.parents.kidsguard.common.MimamoriPhoneDlg;
import jp.co.sharp.android.parents.kidsguard.common.OpenBluetoothConfirmDlg;
import jp.co.sharp.android.parents.kidsguard.common.PermissionDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessPointDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessWarningDlg;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.MessageConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestCodeConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestMethodConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestReceiverConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothItemDto;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothReceiverDto;
import jp.co.sharp.android.parents.kidsguard.entity.KidInfoEntity;
import jp.co.sharp.android.parents.kidsguard.utils.CommonUtils;

/**
 * ペアリング設定
 */
public class BluetoothSearchActivity extends Activity {

    private DealWithWaitingDlg mDealWithWaitingDlg;
    private DelDeviceConfirmDlg mDelDeviceConfirmDlg;
    private static final int UNKNOW_BLUETOOTH = 1;
    private static final int KNOW_BLUETOOTH = 2;
    private static final int ALL_BLUETOOTH = 3;
    private static final int PAIRE_BLUETOOTH = 4;
    private ParentBleTransfer mParentBleTransfer;
    private List<BluetoothItemDto> mLsUnKnowBluetoothItemDto;
    private BluetoothItemDto mAddBluetoothItemDto;
    // 0: 初期化 1: onServiceDiscoveryChanged
    private int mBluetoothFlag = 0;
    private App mApp;
    // 1: UNKNOW_BLUETOOTH 2:KNOW_BLUETOOTH 3:ALL_BLUETOOTH 4: PAIRE_BLUETOOTH
    private int mSearchBluetoothFlag = 0;
    private LinearLayout mKnowBluetoothRegion;
    private LinearLayout mUnknowBluetoothRegion;
    private LinearLayout mUnknowBluetoothBody;
    private LinearLayout mUnknowNoneBluetooth;
    // UNKNOW
    private LinearLayout mUnknowNoneBluetoothRegion;
    private ListView mBluetoothUnKnowList;
    private ListView mBluetoothKnowList;
    // 権限CODE
    private final static int LOCATION_PERMISSION_CODE = 1;
    private final static int REQ_PERMISSION_RESULT = 2;
    private String mAction;
    // 0: 認証
    private final static String DEVICE_STATUS_APPROVE = "0";
    // デバイス削除フラグ
    private boolean mDelDeviceFlag = false;
    // -------------------  Mimamori追加 ------------------------------
    // Mimamori 再接続使用するには
    private BluetoothItemDto mBluetoothItemDto;
    private boolean mUnReceiver = true;
    private int mBluetoothConnection = 0;
    private static final int DISCONNECTION_BLUETOOTH = 6;
    private static final int CONNECTION_BLUETOOTH_FAILED = 7;
    private KidInfoEntity mKidInfoEntity;
    // みまもり 開始する
    private final static int MIMAMORI_OPEN = 0;
    // みまもり 終了
    private final static int MIMAMORI_CLOSE = 1;
    // みまもり チェック SIM
    private final static int MIMAMORI_CHECK_SIM = 2;
    // みまもり チェック 連絡先
    private final static int MIMAMORI_CHECK_CONTACTS = 3;
    private boolean mOpenMimamoriWarn = false;
    // OPEN みまもり
    private static final int OPEN_MIMAMORI_CONNECTION_BLUETOOTH = 8;
    // Open みまもり Error
    private static final int OPEN_MIMAMORI_ERROR = 9;
    // Open みまもり Success
    private static final int OPEN_MIMAMORI_SUCCESS = 10;
    // Close みまもり Success
    private static final int CLOSE_MIMAMORI_SUCCESS = 11;

    private boolean mMimamoriError = false;
    private String mPageMacAddress;
    // ページジャンプ
    private boolean mPageJumpFlag = false;
    // プログラムロック
    private String mSyncLock = "syncLock";

    private static final String TAG = "TAG";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(this.TAG, "BluetoothSearchActivity_onCreate");
        setContentView(R.layout.activity_bluetooth_search);

        mApp = (App)getApplication();
        initReceiver();
        initActivity();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(this.TAG, "BluetoothSearchActivity_onStart");
        synchronized (mSyncLock) {
            initReceiver();
            if (!mMimamoriError) {
                initPermissions();
            }
            mApp.setAppStatus(Constants.APP_STATUS_INIT);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(this.TAG, "BluetoothSearchActivity_onStop");
        synchronized (mSyncLock) {
            if (!mUnReceiver) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                try {
                    unregisterReceiver(mimamoriReceiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
                mUnReceiver = true;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(this.TAG, "BluetoothSearchActivity_onDestroy");
        synchronized (mSyncLock) {
            if (!mUnReceiver) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                try {
                    unregisterReceiver(mimamoriReceiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
                mUnReceiver = true;
            }
        }
    }

    /**
     * 初期化Activity
     */
    private void initActivity() {
        Log.i(this.TAG, "BluetoothSearchActivity_initActivity");
        Intent intent = getIntent();
        mAction = intent.getAction();

        mKnowBluetoothRegion = (LinearLayout)findViewById(R.id.knowBluetoothRegion);
        mUnknowBluetoothRegion = (LinearLayout)findViewById(R.id.unknowBluetoothRegion);
        mUnknowBluetoothBody = (LinearLayout)findViewById(R.id.unknowBluetoothBody);
        mUnknowNoneBluetooth = (LinearLayout)findViewById(R.id.unknowNoneBluetooth);
        mUnknowNoneBluetoothRegion = (LinearLayout)findViewById(R.id.unknowNoneBluetoothRegion);
        mBluetoothUnKnowList = (ListView)findViewById(R.id.bluetoothUnKnowList);
        mBluetoothKnowList = (ListView)findViewById(R.id.bluetoothKnowList);

        mUnknowBluetoothBody.setVisibility(View.VISIBLE);
        mUnknowNoneBluetooth.setVisibility(View.GONE);

        ImageView bthSearchBtn = (ImageView)findViewById(R.id.btnBluetoothSearch);
        bthSearchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 初期化
                mLsUnKnowBluetoothItemDto = new ArrayList<>();

                mUnknowBluetoothBody.setVisibility(View.VISIBLE);
                mUnknowNoneBluetooth.setVisibility(View.GONE);
                mUnknowNoneBluetoothRegion.setVisibility(View.GONE);

                if (!checkBluetoothState()) {
                    OpenBluetoothConfirmDlg openBluetoothConfirmDlg = new OpenBluetoothConfirmDlg(BluetoothSearchActivity.this, R.style.commonDlg);
                    openBluetoothConfirmDlg.show();
                    openBluetoothConfirmDlg.setOnOperateSetListener(new OpenBluetoothConfirmDlg.OnOperateSetListener() {
                        @Override
                        public void onOperateSet() {
                            openBluetoothConfirmDlg.dismiss();
                            startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS)); //直接进入手机中的蓝牙设置界面
                        }
                    });
                    return;
                } else {
                    initBluetoothSearch();
                }
            }
        });

        if (intent.hasExtra(Constants.KEY_KID_MAC_ADDRESS)) {
            mPageMacAddress = intent.getStringExtra(Constants.KEY_KID_MAC_ADDRESS);
            KidInfoEntity kidInfoEntity = new KidInfoEntity();
            kidInfoEntity.setMacAddress(mPageMacAddress);
            new DisconnectBluetoothThread(kidInfoEntity).start();
        }
    }

    /**
     * 初期化Receiver
     */
    private void initReceiver() {
        Log.i(this.TAG, "BluetoothSearchActivity_initReceiver");

        IntentFilter filter = new IntentFilter();
        // ロック画面
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        // 画面を開く
        filter.addAction(Intent.ACTION_USER_PRESENT);
        // ホームボタン
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);

        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_SEARCH);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_SERVICE_DISCOVERY_CHANGED);

        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED);
        registerReceiver(receiver, filter);
        registerReceiver(mimamoriReceiver, filter);
        registerReceiver(systemReceiver, filter);
        this.mParentBleTransfer = ((App)getApplication()).getmParentBleTransfer();
        mUnReceiver = false;
    }

    /**
     * システム放送
     */
    private final BroadcastReceiver systemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_SCREEN_OFF);
                    }
                } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_USER_PRESENT);
                        // ブロードキャストの再登録
                        unregisterReceiver(systemReceiver);
                        initReceiver();
                    }
                } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_CLOSE_SYSTEM_DIALOGS);
                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                    // Bluetoothステータス監視
                    // 初期化
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String macAddress = bluetoothReceiverDto.getAddress();
                    if (bluetoothReceiverDto.getStatus() == Constants.STATUS_BLUETOOTH_DISCONNECTION &&
                            bluetoothReceiverDto.getReson() == Constants.REASON_BLUETOOTH_USER_DISCONNECTION) {
                        // Mimamori 起こるかもしれない
                        Message msg = new Message();
                        msg.what = DISCONNECTION_BLUETOOTH;
                        msg.obj = macAddress;
                        mimamoriOtherHandler.sendMessage(msg);
                    }
                } else if (Intent.ACTION_NEW_OUTGOING_CALL.equals(action)) {

                } else {
                    TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE);
                    telephonyManager.listen(new PhoneStateListener(){
                        @Override
                        public void onCallStateChanged(int state, String incomingNumber) {
                            super.onCallStateChanged(state, incomingNumber);
                            /*Intent freshIntent = new Intent();*/
                            switch(state){
                                case TelephonyManager.CALL_STATE_IDLE:
                                    CommonUtils.stopRingtone(null, null);
                                    CommonUtils.stopVibrator(null);
//                    freshIntent.setAction("com.android.music.musicservicecommand.pause");
//                    freshIntent.putExtra("command", "pause");
//                    mContext.sendBroadcast(freshIntent);
                                    break;
                                case TelephonyManager.CALL_STATE_OFFHOOK:
                                    CommonUtils.stopRingtone(null, null);
                                    CommonUtils.stopVibrator(null);
                                    break;
                                case TelephonyManager.CALL_STATE_RINGING:
                                    CommonUtils.stopRingtone(null, null);
                                    CommonUtils.stopVibrator(null);
//                    freshIntent.setAction("com.android.music.musicservicecommand.pause");
//                    freshIntent.putExtra("command", "pause");
//                    mContext.sendBroadcast(freshIntent);
                                    break;
                            }
                        }
                    }, PhoneStateListener.LISTEN_CALL_STATE);
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };

    /**
     * 許可を確認した後のBluetoothデバイスの取得
     */
    private void initBluetoothSearch() {
        Log.i(this.TAG, "BluetoothSearchActivity_initBluetoothSearch");

        if (null != mAction && mAction.equals(Constants.ACTION_KID_BLUETOOTH)) {
            // 検索中...
            String pDlgMsg = "検索中...";
            mDealWithWaitingDlg = new DealWithWaitingDlg(this, R.style.dealWithWaitingDlg, pDlgMsg, false);
            mDealWithWaitingDlg.show();

            mUnknowBluetoothRegion.setVisibility(View.VISIBLE);
            mUnknowNoneBluetoothRegion.setVisibility(View.GONE);
            // 既存の機器が存在するかどうか
            if (mApp.getMaxKidInfo() == 0) {
                // 既存のデバイスは存在しません
                mKnowBluetoothRegion.setVisibility(View.GONE);
                mSearchBluetoothFlag = UNKNOW_BLUETOOTH;
            } else {
                // 既存のデバイスが存在する
                mKnowBluetoothRegion.setVisibility(View.VISIBLE);
                mSearchBluetoothFlag = ALL_BLUETOOTH;
            }
            // ALL
            new BluetoothSearchThread(mSearchBluetoothFlag).start();
        } else {
            mUnknowBluetoothRegion.setVisibility(View.VISIBLE);
            mUnknowNoneBluetoothRegion.setVisibility(View.GONE);
            // 検索中...
            String pDlgMsg = "検索中...";
            mDealWithWaitingDlg = new DealWithWaitingDlg(this, R.style.dealWithWaitingDlg, pDlgMsg,false);
            mDealWithWaitingDlg.show();
            mSearchBluetoothFlag = UNKNOW_BLUETOOTH;
            // ALL
            new BluetoothSearchThread(mSearchBluetoothFlag).start();
        }
    }

    /**
     * ペアリング検索
     */
    private class BluetoothSearchThread extends Thread {
        private int searchFlag = 0;
        public BluetoothSearchThread (int pSearchFlag) {
            this.searchFlag = pSearchFlag;
        }
        @Override
        public void run() {
            try {
                mParentBleTransfer.enableScanLeDevice(true);
                sleep(5000L);
                mParentBleTransfer.enableScanLeDevice(false);

                Message msg = new Message();
                msg.what = searchFlag;
                handler.sendMessage(msg);
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    }

    /**
     * ペアリング検索
     */
    private void bluetoothSearch(int pSearchFlag) {
        Log.i(this.TAG, "BluetoothSearchActivity_bluetoothSearch");
        try {
            if (pSearchFlag == UNKNOW_BLUETOOTH || pSearchFlag == ALL_BLUETOOTH) {
                if (null == mLsUnKnowBluetoothItemDto || mLsUnKnowBluetoothItemDto.isEmpty()) {
                    if (pSearchFlag == UNKNOW_BLUETOOTH ) {
                        mUnknowNoneBluetoothRegion.setVisibility(View.VISIBLE);
                        mUnknowBluetoothRegion.setVisibility(View.GONE);
                    } else {
                        mUnknowBluetoothRegion.setVisibility(View.VISIBLE);
                        mUnknowNoneBluetoothRegion.setVisibility(View.GONE);
                        mUnknowBluetoothBody.setVisibility(View.GONE);
                        mUnknowNoneBluetooth.setVisibility(View.VISIBLE);
                    }
                } else {
                    BluetoothItemUnknowAdapter bluetoothItemUnknowAdapter =
                            new BluetoothItemUnknowAdapter(BluetoothSearchActivity.this, R.layout.activity_bluetooth_search_unknow_item, mLsUnKnowBluetoothItemDto);
                    mBluetoothUnKnowList.setAdapter(bluetoothItemUnknowAdapter);

                    mBluetoothUnKnowList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            // 5台のキッズケータイ
                            if (mApp.getMaxKidInfo() == 5) {
                                ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(BluetoothSearchActivity.this, R.style.commonDlg, MessageConstants.MSG_BTH_SEARCH_MAX_DEVICE_ERROR);
                                processWarringDlg.show();
                                processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                    @Override
                                    public void onOperateSet() {
                                        processWarringDlg.dismiss();
                                    }
                                });
                                return;
                            }
                            if (!checkBluetoothState()) {
                                OpenBluetoothConfirmDlg openBluetoothConfirmDlg = new OpenBluetoothConfirmDlg(BluetoothSearchActivity.this, R.style.commonDlg);
                                openBluetoothConfirmDlg.show();
                                openBluetoothConfirmDlg.setOnOperateSetListener(new OpenBluetoothConfirmDlg.OnOperateSetListener() {
                                    @Override
                                    public void onOperateSet() {
                                        openBluetoothConfirmDlg.dismiss();
                                        startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS)); //直接进入手机中的蓝牙设置界面
                                    }
                                });
                                return;
                            }
                            mAddBluetoothItemDto = new BluetoothItemDto();
                            mAddBluetoothItemDto = mLsUnKnowBluetoothItemDto.get(i);
                            //接続中...
                            String pDlgMsg = "接続中...";
                            mDealWithWaitingDlg = new DealWithWaitingDlg(BluetoothSearchActivity.this, R.style.dealWithWaitingDlg, pDlgMsg, false);
                            mDealWithWaitingDlg.show();
                            new ConnectBluetoothThread().start();
                        }
                    });
                }
            }
            if (pSearchFlag == KNOW_BLUETOOTH || pSearchFlag == ALL_BLUETOOTH) {
                List<KidInfoEntity> lsKidInfoEntity = mApp.getCacheEntity().getKidLists();
                // 既存のデバイスは存在しません
                if (null == lsKidInfoEntity || lsKidInfoEntity.isEmpty()) {
                    mKnowBluetoothRegion.setVisibility(View.GONE);
                }
                final List<BluetoothItemDto> lsBluetoothItemDto = new ArrayList<>();
                // Max 5
                for (KidInfoEntity kidInfoEntity : lsKidInfoEntity) {
                    BluetoothItemDto bluetoothItemDto = new BluetoothItemDto(
                            kidInfoEntity.getBtName(),
                            kidInfoEntity.getMacAddress(),
                            kidInfoEntity.getMacId(),
                            kidInfoEntity.getKidName());
                    lsBluetoothItemDto.add(bluetoothItemDto);
                }
                mBluetoothKnowList.setAdapter(new BluetoothItemKnowAdapter(BluetoothSearchActivity.this,
                        R.layout.activity_bluetooth_search_know_item , lsBluetoothItemDto,
                        new BluetoothItemKnowAdapter.OnDelBluetoothListenter() {
                            @Override
                            public void delBluetoothClick(int postition, View v) {
                                //接続中...
                                BluetoothItemDto bluetoothItemDto = lsBluetoothItemDto.get(postition);
                                // みまもりデバイスの確認を削除する
                                if (mApp.isMimamoriCheckByMacId(bluetoothItemDto.getMacId())) {
                                    ProcessWarningDlg processWarningDlg = new ProcessWarningDlg(BluetoothSearchActivity.this, R.style.commonDlg, MessageConstants.MSG_MIMAMORI_DEVICE_DELETE_ERROR);
                                    processWarningDlg.show();
                                    processWarningDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                        @Override
                                        public void onOperateSet() {
                                            processWarningDlg.dismiss();
                                        }
                                    });
                                    return;
                                }
                                // デバイスの確認を削除する
                                mDelDeviceConfirmDlg = new DelDeviceConfirmDlg(BluetoothSearchActivity.this,
                                        R.style.commonDlg ,
                                        MessageFormat.format(MessageConstants.MSG_BTH_SEARCH_DEVICE_DELETE, bluetoothItemDto.getDeviceNickName()));
                                mDelDeviceConfirmDlg.show();
                                mDelDeviceConfirmDlg.setOnOperateSetListener(new DelDeviceConfirmDlg.OnOperateSetListener() {
                                    @Override
                                    public void onOperateSet() {
                                        KidInfoEntity kidInfoEntity = mApp.findKidInfoByMacId(bluetoothItemDto.getMacId());
                                        if (kidInfoEntity.getBtConnStatus().equals(Constants.DEVICE_CONNECTION_SUCCESS)) {
                                            delDeviceDealWith(kidInfoEntity);
                                        } else {
                                            mApp.deleteKidInfo(kidInfoEntity);
                                            mDelDeviceConfirmDlg.dismiss();
                                            bluetoothSearch(mSearchBluetoothFlag);
                                        }
                                    }
                                });
                            }
                        }));
            }
        } catch ( Exception e) {
            Log.e(this.TAG, e.getMessage());
        } finally {
            handler.sendEmptyMessage(0);
        }
    }

    /**
     * Bluetoothデバイスの処理を削除する
     * @param pKidInfoEntity
     */
    private void delDeviceDealWith(KidInfoEntity pKidInfoEntity) {
        // Bluetoothチェック
        if (!checkBluetoothState()) {
            if (mDelDeviceConfirmDlg.isShowing()) {
                mDelDeviceConfirmDlg.dismiss();
            }
            OpenBluetoothConfirmDlg openBluetoothConfirmDlg = new OpenBluetoothConfirmDlg(BluetoothSearchActivity.this, R.style.commonDlg);
            openBluetoothConfirmDlg.show();
            openBluetoothConfirmDlg.setOnOperateSetListener(new OpenBluetoothConfirmDlg.OnOperateSetListener() {
                @Override
                public void onOperateSet() {
                    openBluetoothConfirmDlg.dismiss();
                    startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS)); //直接进入手机中的蓝牙设置界面
                }
            });
            return;
        } else {
            mDelDeviceFlag = true;
            new DisconnectBluetoothThread(pKidInfoEntity).start();
        }
    }

    /**
     * 接続解除 Thread
     */
    private class DisconnectBluetoothThread extends Thread {
        private KidInfoEntity mKidInfoEntity;
        public DisconnectBluetoothThread(KidInfoEntity pKidInfoEntity) {
            mKidInfoEntity = pKidInfoEntity;
        }
        @Override
        public void run() {
            disconnectBluetooth(mKidInfoEntity);
        }
    }

    /**
     * 接続解除
     * @param pKidInfoEntity
     */
    private void disconnectBluetooth(KidInfoEntity pKidInfoEntity) {
        Log.i(TAG, "BluetoothSearchActivity_disconnectBluetooth");
        this.mParentBleTransfer.disconnectLeDevice(pKidInfoEntity.getMacAddress());
    }

    /**
     * Dialog閉じる
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (0 == msg.what) {
                mDealWithWaitingDlg.dismiss();
            } else if (UNKNOW_BLUETOOTH == msg.what) {
                bluetoothSearch(UNKNOW_BLUETOOTH);
            } else if (KNOW_BLUETOOTH == msg.what) {
                bluetoothSearch(KNOW_BLUETOOTH);
            } else if (ALL_BLUETOOTH == msg.what) {
                bluetoothSearch(ALL_BLUETOOTH);
            } else if (PAIRE_BLUETOOTH == msg.what) {
                mDealWithWaitingDlg.dismiss();
            }
        }
    };

    /**
     * ページリターンキー、フルスクリーンリターンジェスチャー
     */
    @Override
    public void onBackPressed() {
        backActivity(null);
    }

    /**
     * 前のページに戻る(値なし)
     */
    public void backActivity(View view) {
        Log.i(this.TAG, "BluetoothSearchActivity_backActivity");
        if (mApp.getMaxKidInfo() == 0) {
            // ページジャンプ
            mPageJumpFlag = true;
            Intent intent = new Intent();
            intent.setClass(BluetoothSearchActivity.this, BluetoothActivity.class);
            startActivity(intent);
        } else {
            if (null != mAction && mAction.equals(Constants.ACTION_KID_BLUETOOTH)) {
                // ページジャンプ
                mPageJumpFlag = true;
                // HomeパージからSearchパージ
                Intent intent = new Intent();
                intent.setClass(BluetoothSearchActivity.this, HomeActivity.class);
                startActivity(intent);
            } else {
                // ページジャンプ
                mPageJumpFlag = true;
                Intent intent = new Intent();
                intent.setClass(BluetoothSearchActivity.this, BluetoothActivity.class);
                startActivity(intent);
            }
        }
    }

    /**
     *
     */
    private class ConnectBluetoothThread extends Thread {
        @Override
        public void run() {
            try {
                synchronized (mAddBluetoothItemDto) {
                    connectBluetooth(mAddBluetoothItemDto);

                    while (null == mAddBluetoothItemDto.getDeviceStatus()) {
                        mAddBluetoothItemDto.wait(5000L);
                        break;
                    }
                    if (null == mAddBluetoothItemDto.getDeviceStatus()) {
                        // 接続DLGを閉じる
                        handler.sendEmptyMessage(0);
                        String message = "キッズケータイとペアリングできませんでした";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(BluetoothSearchActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {
                                processWarringDlg.dismiss();
                            }
                        });
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    }

    /**
     *
     * @param pBluetoothItemDto
     */
    private void connectBluetooth(BluetoothItemDto pBluetoothItemDto) {
        Log.i(this.TAG, "BluetoothSearchActivity_connectBluetooth");
        this.mParentBleTransfer.connectLeDevice(pBluetoothItemDto.getMacAddress());
    }

    /**
     * BroadcastReceiver
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (!mMimamoriError) {
                if (RequestReceiverConstants.RECEIVER_BLUETOOTH_SEARCH.equals(action)) {
                    // 从intent中获取设备
                    BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String deviceName = device.getName();
                    String macAddress = device.getAddress();
                    byte[] scanRecord = (byte[]) intent.getByteArrayExtra(RequestReceiverConstants.RECEIVER_MAC_ID_KEY);
                    String scanRecordString = new String(scanRecord).trim();
                    String macId = scanRecordString.substring(scanRecordString.length() - 6, scanRecordString.length());

                    boolean existMacId = false;
                    // Know Bluetooth List Check
                    List<KidInfoEntity> lsKidInfoEntity = mApp.getCacheEntity().getKidLists();
                    if (null != lsKidInfoEntity) {
                        for (KidInfoEntity kidInfoEntity : lsKidInfoEntity) {
                            if (null != kidInfoEntity.getMacId() && kidInfoEntity.getMacId().equals(macId)) {
                                existMacId = true;
                            }
                        }
                    }

                    if (!existMacId) {
                        existMacId = false;
                        if (null == mLsUnKnowBluetoothItemDto) {
                            mLsUnKnowBluetoothItemDto = new ArrayList<>();
                        }
                        if (mLsUnKnowBluetoothItemDto.isEmpty()) {
                            BluetoothItemDto bluetoothItemDto = new BluetoothItemDto(deviceName, macAddress, macId, null);
                            mLsUnKnowBluetoothItemDto.add(bluetoothItemDto);
                        } else {
                            for (BluetoothItemDto bluetoothItemDto : mLsUnKnowBluetoothItemDto) {
                                if (bluetoothItemDto.getMacId().equals(macId)) {
                                    existMacId = true;
                                    break;
                                }
                            }
                            if (!existMacId) {
                                BluetoothItemDto bluetoothItemDto = new BluetoothItemDto(deviceName, macAddress, macId,null);
                                mLsUnKnowBluetoothItemDto.add(bluetoothItemDto);
                            }
                        }
                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                    // 初期化
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    if (bluetoothReceiverDto.getStatus() == Constants.STATUS_BLUETOOTH_CONNECTION) {
                        mBluetoothFlag = Constants.STATUS_BLUETOOTH_CONNECTION;
                        synchronized (mAddBluetoothItemDto) {
                            mAddBluetoothItemDto.setDeviceStatus(DEVICE_STATUS_APPROVE);
                            mAddBluetoothItemDto.notify();
                        }
                    } else {
                        // Mimamori Check
                        String macAddress = bluetoothReceiverDto.getAddress();
                        if (bluetoothReceiverDto.getStatus() == Constants.STATUS_BLUETOOTH_DISCONNECTION &&
                                bluetoothReceiverDto.getReson() == Constants.REASON_BLUETOOTH_USER_DISCONNECTION) {
                            // Mimamori 起こるかもしれない
                            Message msg = new Message();
                            msg.what = DISCONNECTION_BLUETOOTH;
                            msg.obj = macAddress;
                            mimamoriOtherHandler.sendMessage(msg);
                        } else {
                            handler.sendEmptyMessage(0);
                            String message = "キッズケータイとペアリングできませんでした";
                            ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(BluetoothSearchActivity.this, R.style.commonDlg, message);
                            processWarringDlg.show();
                            processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                @Override
                                public void onOperateSet() {
                                    processWarringDlg.dismiss();
                                }
                            });
                        }
                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_SERVICE_DISCOVERY_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);

                    if (mBluetoothFlag == Constants.STATUS_BLUETOOTH_CONNECTION && bluetoothReceiverDto.isDiscoveryState()) {
                        mBluetoothFlag = 0;
                        Message msg = new Message();
                        msg.what = PAIRE_BLUETOOTH;
                        handler.sendMessage(msg);

                        // ページジャンプ
                        mPageJumpFlag = true;
                        Intent intent1 = new Intent();
                        intent1.setClass(BluetoothSearchActivity.this, BluetoothPairingActivity.class);
                        // ジャンプするページを検出する
                        if (null != mAction) {
                            intent1.setAction(mAction);
                        }
                        intent1.putExtra(Constants.KEY_ADD_BLUETOOTH, mAddBluetoothItemDto);
                        startActivity(intent1);
                    }
                }
            } else {
                // TODO Mimamori
                if (RequestReceiverConstants.RECEIVER_BLUETOOTH_SEARCH.equals(action)) {
                    // 从intent中获取设备
                    BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String deviceName = device.getName();
                    String macAddress = device.getAddress();
                    byte[] scanRecord = (byte[]) intent.getByteArrayExtra(RequestReceiverConstants.RECEIVER_MAC_ID_KEY);
                    String scanRecordString = new String(scanRecord).trim();
                    String macId = scanRecordString.substring(scanRecordString.length() - 6, scanRecordString.length());

                    if (macId.equals(mKidInfoEntity.getMacId())) {
                        synchronized (mBluetoothItemDto) {
                            mBluetoothItemDto.setMacId(macId);
                            mBluetoothItemDto.setMacAddress(macAddress);
                            mBluetoothItemDto.setBluetoothName(deviceName);
                            mBluetoothItemDto.notify();
                        }
                    }

                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                    // 初期化
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String macAddress = bluetoothReceiverDto.getAddress();
                    if (bluetoothReceiverDto.getStatus() == Constants.STATUS_BLUETOOTH_CONNECTION) {
                        mBluetoothFlag = Constants.STATUS_BLUETOOTH_CONNECTION;
                    } else if (bluetoothReceiverDto.getStatus() == Constants.STATUS_BLUETOOTH_DISCONNECTION &&
                            bluetoothReceiverDto.getReson() == Constants.REASON_BLUETOOTH_USER_DISCONNECTION) {
                        // Mimamori 起こるかもしれない
                        Message msg = new Message();
                        msg.what = DISCONNECTION_BLUETOOTH;
                        msg.obj = macAddress;
                        mimamoriOtherHandler.sendMessage(msg);
                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_SERVICE_DISCOVERY_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    if (mBluetoothFlag == Constants.STATUS_BLUETOOTH_CONNECTION && bluetoothReceiverDto.isDiscoveryState()) {
                        mBluetoothFlag = 0;
                        Message msg = new Message();
                        msg.what = mBluetoothConnection;
                        mimamoriOtherHandler.sendMessage(msg);
                    }
                }
            }

        }
    };

    /**
     * bluetooth status
     * @return true: Open  false: Close
     */
    private boolean checkBluetoothState() {
        Log.i(this.TAG, "BluetoothSearchActivity_checkBluetoothState");
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (null != bluetoothAdapter) {
            if (bluetoothAdapter.isEnabled()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 権限を確認してください
     */
    @TargetApi(Build.VERSION_CODES.M)
    private void initPermissions() {
        Log.i(this.TAG, "BluetoothSearchActivity_initPermissions");
        // Android バージョン番号
        int version = android.os.Build.VERSION.SDK_INT;
        if (version >= 23) {
            if ((checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) ||
                    (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
                requestPermissions(new String[]{ Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_CODE);
            } else {
                initBluetoothSearch();
            }
        } else {
            initBluetoothSearch();
        }
    }

    /**
     * 権限を確認してください
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        Log.i(this.TAG, "BluetoothSearchActivity_onRequestPermissionsResult");
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Boolean phonePermissionFlag = false;
        Boolean storagePermissionFlag = false;
        if (requestCode == this.LOCATION_PERMISSION_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                phonePermissionFlag = true;
            } else {
                if (shouldShowRequestPermissionRationale(permissions[0])){
                    Toast.makeText(this, "Location Permissionの権限が必要です。アクセス権限を付与してください", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:jp.co.sharp.android.parents.kidsguard"));
                    PermissionDlg permissionDlg = new PermissionDlg(BluetoothSearchActivity.this, R.style.commonDlg);
                    permissionDlg.show();
                    permissionDlg.setOnOperateSetListener(new PermissionDlg.OnOperateSetListener() {
                        @Override
                        public void onOperateSet() {
                            startActivityForResult(intent,1000);
                        }
                    });
                }
            }
            if (grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                storagePermissionFlag = true;
            } else {
                if (shouldShowRequestPermissionRationale(permissions[1])){
                    Toast.makeText(this, "Location Permissionの権限が必要です。アクセス権限を付与してください", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:jp.co.sharp.android.parents.kidsguard"));
                    PermissionDlg permissionDlg = new PermissionDlg(BluetoothSearchActivity.this, R.style.commonDlg);
                    permissionDlg.show();
                    permissionDlg.setOnOperateSetListener(new PermissionDlg.OnOperateSetListener() {
                        @Override
                        public void onOperateSet() {
                            permissionDlg.dismiss();
                            startActivityForResult(intent, REQ_PERMISSION_RESULT);
                        }
                    });
                }
            }
        }
        if(storagePermissionFlag && phonePermissionFlag) {
            initBluetoothSearch();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        Log.i(this.TAG, "BluetoothSearchActivity_onActivityResult");
        if (requestCode == REQ_PERMISSION_RESULT) {
            initPermissions();
        }
    }

    /*------------------------------------------------------- Mimamori 追加---------------------------------------------------------------------*/

    /**
     * デバイス 接続
     * @param pConnectionFlag  OPEN みまもり設定
     */
    private void connectDevice(int pConnectionFlag) {
        Log.i(this.TAG, "BluetoothSearchActivity_connectDevice");
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (null != bluetoothAdapter) {
            if (!bluetoothAdapter.isEnabled()) {
                OpenBluetoothConfirmDlg openBluetoothConfirmDlg = new OpenBluetoothConfirmDlg(BluetoothSearchActivity.this, R.style.commonDlg);
                openBluetoothConfirmDlg.show();
                openBluetoothConfirmDlg.setOnOperateSetListener(new OpenBluetoothConfirmDlg.OnOperateSetListener() {
                    @Override
                    public void onOperateSet() {
                        openBluetoothConfirmDlg.dismiss();
                        startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS)); //直接进入手机中的蓝牙设置界面
                    }
                });
            } else {
                this.mBluetoothConnection = pConnectionFlag;

                String pDlgMsg = "接続中...";
                mDealWithWaitingDlg = new DealWithWaitingDlg(BluetoothSearchActivity.this, R.style.dealWithWaitingDlg, pDlgMsg, false);
                mDealWithWaitingDlg.show();
                new ConnectMimamoriBthThread().start();
            }
        }
    }

    /**
     * 接続Thread
     */
    private class ConnectMimamoriBthThread extends Thread {

        @Override
        public void run() {
            try {
                mBluetoothItemDto = new BluetoothItemDto();
                synchronized (mBluetoothItemDto) {
                    mParentBleTransfer.enableScanLeDevice(true);
                    while (null == mBluetoothItemDto.getMacId()) {
                        mBluetoothItemDto.wait(7000L);
                        mParentBleTransfer.enableScanLeDevice(false);
                        if (mBluetoothItemDto.getMacId() == null) {
                            Message msg = new Message();
                            msg.what = CONNECTION_BLUETOOTH_FAILED;
                            handler.sendMessage(msg);
                        }
                        break;
                    }
                    if (null != mBluetoothItemDto.getMacId()) {
                        connectMimamoriBth(mBluetoothItemDto);
                        mBluetoothItemDto.wait(3000L);
                        if (!Constants.DEVICE_CONNECTION_SUCCESS.equals(mKidInfoEntity.getBtConnStatus())) {
                            Message msg = new Message();
                            msg.what = CONNECTION_BLUETOOTH_FAILED;
                            handler.sendMessage(msg);
                        }
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    }

    /**
     * 接続
     * @param pBluetoothItemDto
     */
    private void connectMimamoriBth(BluetoothItemDto pBluetoothItemDto) {
        Log.i(this.TAG, "BluetoothSearchActivity_connectMimamoriBth");
        this.mParentBleTransfer.connectLeDevice(pBluetoothItemDto.getMacAddress());
    }

    /*------------------------------------------------------- Mimamori 外で---------------------------------------------------------------------*/
    Handler mimamoriOtherHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (0 == msg.what) {
                mDealWithWaitingDlg.dismiss();
            } else if (DISCONNECTION_BLUETOOTH == msg.what) {
                if (null != mPageMacAddress) {
                    mPageMacAddress = null;
                    return;
                }
                //
                KidInfoEntity kidInfoEntity = mApp.findKidInfoByMacAddress((String) msg.obj);
                if (null != kidInfoEntity) {
                    kidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                    mApp.updateKidInfo(kidInfoEntity);
                }

                //  デバイスが削除されているかどうかを判断する
                if (mDelDeviceFlag && null != kidInfoEntity) {
                    mApp.deleteKidInfo(kidInfoEntity);
                    if (mDelDeviceConfirmDlg.isShowing()) {
                        mDelDeviceConfirmDlg.dismiss();
                    }
                    bluetoothSearch(mSearchBluetoothFlag);
                    mDelDeviceFlag = false;
                }

                // TODO Mimmoriが発生するかどうかを判断する
                if (null != kidInfoEntity && kidInfoEntity.getControlled()) {
                    mMimamoriError = true;
                    if(!mApp.getmLsIsMimamori().contains((String) msg.obj)) {
                        mApp.addmLsIsMimamori((String) msg.obj);
                        isMimamoriChance();
                    }
                }

            } else if (OPEN_MIMAMORI_CONNECTION_BLUETOOTH == msg.what) {
                // Open みまもり設定
                mKidInfoEntity.setMacAddress(mBluetoothItemDto.getMacAddress());
                mKidInfoEntity.setBtConnStatus(Constants.DEVICE_CONNECTION_SUCCESS);
                mApp.updateKidInfo(mKidInfoEntity);
                mDealWithWaitingDlg.dismiss();
                mimamoriProcess(MIMAMORI_OPEN);

                // ウェイクの処理
                synchronized (mBluetoothItemDto) {
                    mBluetoothItemDto.notify();
                }
            }
        }
    };

    /*------------------------------------------------------- Mimamori TODO---------------------------------------------------------------------*/
    /**
     * Mimamori
     * @param pMimamoriStep 0:みまもり 開始する 1:みまもり 終了
     */
    private void mimamoriProcess(int pMimamoriStep) {
        Log.i(this.TAG, "BluetoothSearchActivity_mimamoriProcess");
        // 開く
        if(pMimamoriStep == MIMAMORI_OPEN) {
            // 接続バテン
            if (Constants.DEVICE_DISCONNECTION_FAILED.equals(mKidInfoEntity.getBtConnStatus())
                    || Constants.DEVICE_DISCONNECTION_SUCCESS.equals(mKidInfoEntity.getBtConnStatus())) {
                connectDevice(OPEN_MIMAMORI_CONNECTION_BLUETOOTH);
                return;
            }

            if (mKidInfoEntity.getNeverShow() || mOpenMimamoriWarn) {
                mOpenMimamoriWarn = false;
                String pDlgMsg = "起動中...";
                mDealWithWaitingDlg = new DealWithWaitingDlg(BluetoothSearchActivity.this, R.style.dealWithWaitingDlg, pDlgMsg, false);
                mDealWithWaitingDlg.show();
                new MimamoriThread(MIMAMORI_CHECK_CONTACTS).start();
            } else {
                ProcessPointDlg processPointDlg = new ProcessPointDlg(BluetoothSearchActivity.this, R.style.commonDlg, MessageConstants.MSG_MIMAMORI);
                processPointDlg.show();
                processPointDlg.setOnOperateSetListener(new ProcessPointDlg.OnOperateSetListener() {
                    @Override
                    public void onOperateSet(boolean cbViewDlg) {
                        if (cbViewDlg) {
                            mKidInfoEntity.setNeverShow(true);
                            mApp.updateKidInfo(mKidInfoEntity);
                        }
                        processPointDlg.dismiss();

                        String pDlgMsg = "起動中...";
                        mDealWithWaitingDlg = new DealWithWaitingDlg(BluetoothSearchActivity.this, R.style.dealWithWaitingDlg, pDlgMsg, false);
                        mDealWithWaitingDlg.show();
                        new MimamoriThread(MIMAMORI_CHECK_CONTACTS).start();;
                    }
                });
            }
            // 閉じる
        } else if (pMimamoriStep == MIMAMORI_CLOSE) {
            new MimamoriThread(MIMAMORI_CLOSE).start();
        }

    }

    /**
     * Mimamori 設定　自分の電話番号チェック
     */
    private void mimamoriPhoneNumCheck() {
        Log.i(this.TAG, "BluetoothSearchActivity_mimamoriPhoneNumCheck");
        if (null == mKidInfoEntity.getParentTel() || "".equals(mKidInfoEntity.getParentTel())) {
            if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                mDealWithWaitingDlg.dismiss();
            }
            ProcessWarningDlg processWarningDlg = new ProcessWarningDlg(BluetoothSearchActivity.this, R.style.commonDlg, MessageConstants.MSG_CHECK_PHONE_NUM_NONE);
            processWarningDlg.show();
            processWarningDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                @Override
                public void onOperateSet() {
                    processWarningDlg.dismiss();
                }
            });
        } else {
            new MimamoriThread(MIMAMORI_OPEN).start();;
        }
    }

    /**
     * Mimamori Thread
     */
    private class MimamoriThread extends Thread {
        private int mMimamoriStep;
        public MimamoriThread(int pMimamoriStep) {
            this.mMimamoriStep = pMimamoriStep;
        }

        @Override
        public void run() {
            switch (mMimamoriStep) {
                case MIMAMORI_OPEN:
                    try {
                        mBluetoothItemDto = new BluetoothItemDto();
                        synchronized (mBluetoothItemDto) {
                            openMimamori();
                            while (!mBluetoothItemDto.isMimamoriState()) {
                                mBluetoothItemDto.wait(10000L);
                                if (!mBluetoothItemDto.isMimamoriState()) {
                                    Message msg = new Message();
                                    msg.what = OPEN_MIMAMORI_ERROR;
                                    mimamoriHandler.sendMessage(msg);
                                }
                                break;
                            }
                        }
                    } catch (Exception e) {
                        Log.e(TAG, e.getMessage());
                    }
                    break;
                case MIMAMORI_CLOSE:
                    closeMimamori();
                    break;
                case MIMAMORI_CHECK_SIM:
                    kidSimCardCheck();
                    break;
                case MIMAMORI_CHECK_CONTACTS:
                    kidContactsCheck();
                    break;
            }
        }
    }

    /**
     * Mimamori キッズケータイの電話番号チェック
     */
    private void kidSimCardCheck() {
        Log.i(this.TAG, "BluetoothSearchActivity_kidSimCardCheck");
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", RequestMethodConstants.METHOD_ISDOCOMO_SIM_CARD_INSERT);
            jsonObject.put("data", JSONObject.NULL);

            this.mParentBleTransfer.writeLeData(mKidInfoEntity.getMacAddress(), jsonObject.toString());
        } catch (Exception e) {
            Log.e(this.TAG, e.getMessage());
        }
    }

    /**
     * Mimamori お使いのスマートフォンの電話番号がキッズケータイに登録されていません。
     */
    private void kidContactsCheck() {
        Log.i(this.TAG, "BluetoothSearchActivity_kidContactsCheck");
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", RequestMethodConstants.METHOD_GET_CONTACTS);
            jsonObject.put("data", JSONObject.NULL);

            this.mParentBleTransfer.writeLeData(mKidInfoEntity.getMacAddress(), jsonObject.toString());
        } catch (Exception e) {
            Log.e(this.TAG, e.getMessage());
        }
    }
    /**
     * Mimamori 開く
     */
    private void openMimamori() {
        Log.i(this.TAG, "BluetoothSearchActivity_openMimamori");
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", RequestMethodConstants.METHOD_SET_MIMAMORI_STATE);
            JSONObject jsonData = new JSONObject();
            jsonData.put("state", 0);
            jsonData.put("phone", mKidInfoEntity.getParentTel());
            jsonObject.put("data", jsonData);

            this.mParentBleTransfer.writeLeData(mKidInfoEntity.getMacAddress(), jsonObject.toString());
        } catch (Exception e) {
            Log.e(this.TAG, e.getMessage());
        }
    }

    /**
     * Mimamori 閉じる
     */
    private void closeMimamori() {
        Log.i(this.TAG, "BluetoothSearchActivity_closeMimamori");
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", RequestMethodConstants.METHOD_SET_MIMAMORI_STATE);
            JSONObject jsonData = new JSONObject();
            jsonData.put("state", 1);
            jsonData.put("phone", mKidInfoEntity.getParentTel());
            jsonObject.put("data", jsonData);

            this.mParentBleTransfer.writeLeData(mKidInfoEntity.getMacAddress(), jsonObject.toString());
        } catch (Exception e) {
            Log.e(this.TAG, e.getMessage());
        }
    }

    /**
     * BroadcastReceiver
     */
    private final BroadcastReceiver mimamoriReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    if (bluetoothReceiverDto.isFinished()) {

                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String retStr = bluetoothReceiverDto.getRetStr();
                    JSONObject jsonObject = new JSONObject(retStr);
                    if (RequestMethodConstants.METHOD_ON_SYNC_RESULT.equals(jsonObject.getString("method"))) {
                        if (jsonObject.getString("result").equals(Constants.ON_SYNC_RESULT)) {
                            Message msg = new Message();
                            msg.what = CLOSE_MIMAMORI_SUCCESS;
                            mimamoriHandler.sendMessage(msg);
                        }
                    } else  if (RequestMethodConstants.METHOD_ON_GET_KID_PHONE.equals(jsonObject.getString("method"))) {
                        JSONObject jsonData = jsonObject.getJSONObject("data");
                        mBluetoothItemDto.setMimamoriState(true);
                        mBluetoothItemDto.setKidPhone(jsonData.getString("phone"));

                        Message msg = new Message();
                        msg.what = OPEN_MIMAMORI_SUCCESS;
                        mimamoriHandler.sendMessage(msg);
                    } else if (RequestMethodConstants.METHOD_GET_CONTACTS.equals(jsonObject.getString("method"))) {
                        if (jsonObject.isNull("data")) {
                            Message msg = new Message();
                            msg.what = MIMAMORI_CHECK_CONTACTS;
                            mimamoriHandler.sendMessage(msg);
                        } else {
                            JSONArray jsonArray = jsonObject.getJSONArray("data");
                            if (null != jsonArray && jsonArray.length() > 0) {
                                boolean exist = false;
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject jsonItem = jsonArray.getJSONObject(i);
                                    if (jsonItem.getString("phone").equals(mKidInfoEntity.getParentTel())) {
                                        exist = true;
                                        break;
                                    }
                                }
                                if (!exist) {
                                    Message msg = new Message();
                                    msg.what = MIMAMORI_CHECK_CONTACTS;
                                    mimamoriHandler.sendMessage(msg);
                                } else {
                                    new MimamoriThread(MIMAMORI_CHECK_SIM).start();
                                }
                            } else {
                                Message msg = new Message();
                                msg.what = MIMAMORI_CHECK_CONTACTS;
                                mimamoriHandler.sendMessage(msg);
                            }
                        }
                    } else if (RequestMethodConstants.METHOD_ISDOCOMO_SIM_CARD_INSERT.equals(jsonObject.getString("method"))) {
                        JSONObject jsonData = jsonObject.getJSONObject("data");
                        if (jsonData.getInt("state") == 0) {
                            mimamoriPhoneNumCheck();
                        } else {
                            Message msg = new Message();
                            msg.what = MIMAMORI_CHECK_SIM;
                            mimamoriHandler.sendMessage(msg);
                        }
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };

    Handler mimamoriHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (OPEN_MIMAMORI_ERROR == msg.what) {
                // Open みまもり Error
                if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                    mDealWithWaitingDlg.dismiss();
                }
                ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(BluetoothSearchActivity.this, R.style.commonDlg, MessageConstants.MSG_MIMAMORI_OPEN_ERROR);
                processWarringDlg.show();
                processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                    @Override
                    public void onOperateSet() {
                        processWarringDlg.dismiss();
                    }
                });
            } else if (OPEN_MIMAMORI_SUCCESS == msg.what) {
                // Open みまもり Success
                mKidInfoEntity.setControlled(true);
                mKidInfoEntity.setKidTel(mBluetoothItemDto.getKidPhone());
                mApp.updateKidInfo(mKidInfoEntity);
                if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                    mDealWithWaitingDlg.dismiss();
                }

                // ウェイクの処理
                synchronized (mBluetoothItemDto) {
                    mBluetoothItemDto.notify();
                }
            } else if (MIMAMORI_CHECK_SIM == msg.what) {
                // Open みまもり Error
                if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                    mDealWithWaitingDlg.dismiss();
                }

                ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(BluetoothSearchActivity.this, R.style.commonDlg, MessageConstants.MSG_CHECK_SIM_CARD_ERROR);
                processWarringDlg.show();
                processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                    @Override
                    public void onOperateSet() {
                        processWarringDlg.dismiss();
                    }
                });
            } else if (MIMAMORI_CHECK_CONTACTS == msg.what) {
                // Open みまもり Error
                if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                    mDealWithWaitingDlg.dismiss();
                }
                Intent intent = new Intent();
                MimamoriConfirmDlg mimamoriConfirmDlg = new MimamoriConfirmDlg(
                        BluetoothSearchActivity.this,
                        R.style.commonDlg,
                        MessageConstants.MSG_CHECK_CONTACTS_ERROR,
                        MessageConstants.MSG_CHECK_CONTACTS_ERROR_CONFIRM,
                        MessageConstants.MSG_CHECK_CONTACTS_ERROR_CANCEL,
                        null);
                mimamoriConfirmDlg.show();
                mimamoriConfirmDlg.setOnConfirmSetListener(new MimamoriConfirmDlg.OnConfirmSetListener() {
                    @Override
                    public void onOperateSet(String pMacId) {
                        mimamoriConfirmDlg.dismiss();
                        intent.setClass(BluetoothSearchActivity.this, MimamoriContactAddActivity.class);
                        // ページジャンプ
                        mPageJumpFlag = true;
                        startActivityForResult(intent, RequestCodeConstants.MIMAMORI_CONTACT_ADD);
                    }
                });
                mimamoriConfirmDlg.setOnCancelSetListener(new MimamoriConfirmDlg.OnCancelSetListener() {
                    @Override
                    public void onOperateSet(String pMacId) {
                        mimamoriConfirmDlg.dismiss();
                    }
                });
            }
        }
    };

    /**
     * Mimamori 起こる
     */
    private void isMimamoriChance() {
        Log.i(this.TAG, "BluetoothSearchActivity_isMimamoriChance");

        List<String> lsIsMimamori = mApp.getmLsIsMimamori();
        if (lsIsMimamori.isEmpty()) {
            return;
        }
        // Mimamori Kid
        String isMimamoriAdr = lsIsMimamori.get(lsIsMimamori.size() - 1);
        Iterator<String> iterator = lsIsMimamori.iterator();
        while(iterator.hasNext()){
            String item = (String)iterator.next();
            if(isMimamoriAdr.equals(item)){
                iterator.remove();
            }
        }
        // 最初に選択したデバイスをキャンセルする
        KidInfoEntity oldKidInfoEntity = mApp.findKidInfoBySelect();
        oldKidInfoEntity.setSelected(false);
        mApp.updateKidInfo(oldKidInfoEntity);
        // 新しく選択したデバイスを設定します
        KidInfoEntity kidInfoEntity = mApp.findKidInfoByMacAddress(isMimamoriAdr);
        kidInfoEntity.setSelected(true);
        kidInfoEntity.setControlled(false);
        mApp.updateKidInfo(kidInfoEntity);
        //
        mKidInfoEntity = kidInfoEntity;

        // 通知音
        if (kidInfoEntity.getRingToneSwitch()) {
            CommonUtils.playRingtone(BluetoothSearchActivity.this, kidInfoEntity.getRingToneUrl());
        }
        // バイブレーション
        if (kidInfoEntity.getShockSwitch()) {
            CommonUtils.playVibrator(BluetoothSearchActivity.this);
        }

        // 緊急ポップアップ通知
        if (mApp.getAppStatus() != Constants.APP_STATUS_INIT) {
            int channelId = mApp.findKidInfoPosition(kidInfoEntity);
            NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
            notificationManager.cancel(channelId);
            Intent intent = new Intent(getIntent());
            PendingIntent pendingIntent = PendingIntent.getActivity(BluetoothSearchActivity.this,0,intent,0);
            if(Build.VERSION.SDK_INT >= 26)
            {
                //当sdk版本大于26
                String description = "ParentApp";
                int importance = NotificationManager.IMPORTANCE_HIGH;
                NotificationChannel channel = new NotificationChannel(String.valueOf(channelId), description, importance);
                notificationManager.createNotificationChannel(channel);
                Notification notification = new Notification.Builder(BluetoothSearchActivity.this, String.valueOf(channelId))
                        .setCategory(Notification.CATEGORY_MESSAGE)
                        .setSmallIcon(R.mipmap.parent_app_icon)
                        .setContentText(MessageFormat.format("{0}とはぐれました。至急確認してください！", kidInfoEntity.getKidName()))
                        .setContentIntent(pendingIntent)
                        .setAutoCancel(true)
                        .setFullScreenIntent(pendingIntent,true)
                        .setVisibility(Notification.VISIBILITY_PUBLIC)
                        .build();
                notificationManager.notify(channelId, notification);
            }
            else
            {
                //当sdk版本小于26
                Notification notification = new NotificationCompat.Builder(BluetoothSearchActivity.this)
                        .setContentText(MessageFormat.format("{0}とはぐれました。至急確認してください！", kidInfoEntity.getKidName()))
                        .setContentIntent(pendingIntent)
                        .setSmallIcon(R.mipmap.parent_app_icon)
                        .setAutoCancel(true)
                        .setFullScreenIntent(pendingIntent,true)
                        .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                        .build();
                notificationManager.notify(channelId, notification);
            }
        }

        // 第三
        MimamoriConfirmDlg mimamoriConfirmDlg = new MimamoriConfirmDlg(
                BluetoothSearchActivity.this,
                R.style.commonDlg,
                MessageFormat.format(MessageConstants.MSG_MIMAMORI_WARN_3, mKidInfoEntity.getKidName()),
                MessageConstants.MSG_MIMAMORI_WARN_3_CONFIRM,
                MessageConstants.MSG_MIMAMORI_WARN_3_CANCEL,
                mKidInfoEntity.getMacId());
        mimamoriConfirmDlg.show();
        mimamoriConfirmDlg.setOnConfirmSetListener(new MimamoriConfirmDlg.OnConfirmSetListener() {
            @Override
            public void onOperateSet(String pMacId) {
                mimamoriConfirmDlg.dismiss();
                // 継続
                connectDevice(OPEN_MIMAMORI_CONNECTION_BLUETOOTH);
            }
        });
        mimamoriConfirmDlg.setOnCancelSetListener(new MimamoriConfirmDlg.OnCancelSetListener() {
            @Override
            public void onOperateSet(String pMacId) {
                if (mApp.getmLsIsMimamori().isEmpty()) {
                    mMimamoriError = false;
                }
                mimamoriConfirmDlg.dismiss();
                mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                mKidInfoEntity.setControlled(false);
                mApp.updateKidInfo(mKidInfoEntity);
            }
        });

        // 第二
        MimamoriPhoneDlg mimamoriPhoneDlg = new MimamoriPhoneDlg(BluetoothSearchActivity.this,
                R.style.commonDlg,
                MessageFormat.format(MessageConstants.MSG_MIMAMORI_WARN_2, mKidInfoEntity.getKidName()),
                MessageConstants.MSG_MIMAMORI_WARN_2_CONFIRM,
                MessageConstants.MSG_MIMAMORI_WARN_2_CANCEL,
                mKidInfoEntity.getMacId());
        mimamoriPhoneDlg.show();
        mimamoriPhoneDlg.setOnConfirmSetListener(new MimamoriPhoneDlg.OnConfirmSetListener() {
            @Override
            public void onOperateSet(String pMacId) {
                mimamoriPhoneDlg.dismiss();
                KidInfoEntity kidInfoItem = mApp.findKidInfoByMacId(pMacId);
                // キッズケータイがかける電話番号
                Intent dialIntent =  new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + kidInfoItem.getKidTel()));
                startActivity(dialIntent);
            }
        });
        mimamoriPhoneDlg.setOnCancelSetListener(new MimamoriPhoneDlg.OnCancelSetListener() {
            @Override
            public void onOperateSet(String pMacId) {
                mimamoriPhoneDlg.dismiss();
                KidInfoEntity kidInfoItem = mApp.findKidInfoByMacId(pMacId);
                // 通知音
                if (kidInfoItem.getRingToneSwitch()) {
                    CommonUtils.stopRingtone(BluetoothSearchActivity.this, kidInfoItem.getRingToneUrl());
                }
                // バイブレーション
                if (kidInfoItem.getShockSwitch()) {
                    CommonUtils.stopVibrator(BluetoothSearchActivity.this);
                }
            }
        });
        mimamoriPhoneDlg.setOnImadocoSetListener(new MimamoriPhoneDlg.OnImadocoSetListener() {
            @Override
            public void onOperateSet(String pMacId) {
                mimamoriPhoneDlg.dismiss();
                Uri uri = Uri.parse("https://imadoco.smt.docomo.ne.jp/location/top_sp");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });

        // 最初の
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (null != bluetoothAdapter && !bluetoothAdapter.isEnabled()) {
            ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(
                    BluetoothSearchActivity.this,
                    R.style.commonDlg,
                    MessageFormat.format(MessageConstants.MSG_MIMAMORI_WARN_1, mKidInfoEntity.getKidName()));
            processWarringDlg.show();
            processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                @Override
                public void onOperateSet() {
                    processWarringDlg.dismiss();
                }
            });
        }
    }
}
